using System;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Users;
using System.IO;
using System.Collections;
using System.Collections.Generic;

namespace Jfc007.WebLib
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditDocuments class is used to manage content
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// </history>
    /// -----------------------------------------------------------------------------
    partial class EditDocuments : PortalModuleBase
    {

        #region Private Members

        private Guid m_fileId = Guid.Empty;

        #endregion
        private void InitializeComponent ( )
        {




        }
        /// <summary>
        /// Upload_ServerClick is the server side script that will upload the files to 
        /// the web server
        /// by looping through the files in the listbox.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Upload_ServerClick ( object sender, System.EventArgs e )
        {
            /*  string baseLocation = "C:\\temp\\";
             string status = "";


            if ((ListBox1.Items.Count == 0) && (filesUploaded == 0))
             {
                 Label1.Text = "Error - a file name must be specified.";
                 return;

             }
             else
             {
                 foreach (System.Web.UI.HtmlControls.HtmlInputFile HIF in hif)
                 {
                     try
                     {
                         string fn = System.IO.Path.GetFileName( HIF.PostedFile.FileName );
                         HIF.PostedFile.SaveAs( baseLocation + fn );
                         filesUploaded++;
                         status += fn + "<br>";
                     }
                     catch (Exception err)
                     {
                         Label1.Text = "Error saving file " + baseLocation
                                                            + "<br>" + err.ToString();
                     }
                 }

                 if (filesUploaded == hif.Count)
                 {
                     Label1.Text = "These " + filesUploaded + " file(s) were "
                                            + "uploaded:<br>" + status;
                 }
                 hif.Clear();
                 ListBox1.Items.Clear();
             }*/
        }
        private void PopulateOwnerList ( )
        {
            // populate owner list
            UserController userController = new UserController();
            lstOwner.DataSource = UserController.GetUsers( PortalId, false );

            lstOwner.DataTextField = "FullName";
            lstOwner.DataValueField = "UserId";

            lstOwner.DataBind();

            // .GetUsers doesn't return super-users, but they can own documents
            // so add them to the list


            foreach (UserInfo objSuperUser in UserController.GetUsers( PortalId ))
            {
                lstOwner.Items.Insert( 0, new System.Web.UI.WebControls.ListItem( objSuperUser.DisplayName, objSuperUser.UserID.ToString() ) );
            }


            lstOwner.Items.Insert( 0, new System.Web.UI.WebControls.ListItem( "None_Specified", "-1" ) );

        }

        #region Event Handlers

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load ( System.Object sender, System.EventArgs e )
        {
            try
            {


                string script = "function mysplit() ";
                script += "{";
                script += "   var temp1 = document.getElementById('" + fileUpload.ClientID + "').value;";
                script += "   var temp2 = null;";
                script += " var  fileName='';";
                script += "  if (temp1.indexOf(':') !=-1)";
                script += "   {";
                script += "     temp1 = temp1.substring(2); ";
                script += "     temp2 = temp1.split(\"\\\\\");";
                script += "   } else {";
                script += "     temp2 = temp1.split('\');";
                script += "   }       ";
                script += "     temp1 = temp2[temp2.length-1];";
                script += "     temp2 = temp1.split('.');";
                script += "      fileName = temp2[0];";
                script += "   return  fileName;";
                script += "};";


                ckbShared.Attributes.Add( "onClick", "javascript:document.getElementById('" + txtShareCode.ClientID + "').disabled = !(document.getElementById('" + ckbShared.ClientID + "').checked) ;" );
                fileUpload.Attributes.Add( "onChange", "javascript:" + script + " document.getElementById('" + txtDescription.ClientID + "').innerHTML = mysplit();" );
                script = "function hide() ";
                script += "{";
                script += "  if (document.getElementById('" + ckbFreeText.ClientID + "').checked)";
                script += "   {";
                script += "     document.getElementById('" + ddlCategories.ClientID + "').style.visibility = 'hidden';";
                script += "     document.getElementById('" + txtCategory.ClientID + "').style.visibility = 'visible';";
                script += "     document.getElementById('" + inputHidden.ClientID + "').value = 'txtCategoryVisible';";
                script += "   } else {";
                script += "     document.getElementById('" + ddlCategories.ClientID + "').style.visibility = 'visible';";
                script += "     document.getElementById('" + txtCategory.ClientID + "').style.visibility = 'hidden';";
                script += "     document.getElementById('" + inputHidden.ClientID + "').value = 'txtCategoryInvisible';";
                script += "   }       ";
                script += "};";
                ckbFreeText.Attributes.Add( "onClick", "javascript:" + script + "hide();" );


                //Determine ItemId of WebLib to Update
                if (this.Request.QueryString["FileId"] != null)
                {
                    this.FileId = new Guid( (string)this.Request.QueryString["fileId"] );
                }

                //If this is the first visit to the page, bind the role data to the datalist
                if (!(Page.IsPostBack))
                {

                    DocumentsController objDocuments = new DocumentsController();


                    List<CategoryInfo> categories = objDocuments.GetCategories( this.PortalId, UserInfo.UserID );

                    if (categories.Count > 0)
                    {
                        ddlCategories.DataSource = categories;
                        ddlCategories.DataTextField = "Category";
                        ddlCategories.DataValueField = "Category";
                        ddlCategories.DataBind();
                    }

                    if (this.FileId != Guid.Empty)
                    {
                        fileUpload.Visible = false;
                        plFile.Visible = false;

                        // Configure category entry as a free-text entry
                        // lstCategory.Visible = false;
                        //txtCategory.Visible = true;

                        // Add the "are you sure" message to the delete button click event
                        cmdDelete.Attributes.Add( "onClick", "javascript:return confirm('" + "Are you sure you want delete this file?" + "');" );


                        // If the page is being requested the first time, determine if an
                        // document itemId value is specified, and if so populate page
                        // contents with the document details
                        if (!(DotNetNuke.Common.Utilities.Null.IsNull( this.FileId )))
                        {

                            // Read document information

                            DocumentInfo objDocument = objDocuments.GetDocument( this.FileId );

                            // Read values from documentInfo object on to page
                            if (objDocument != null)
                            {

                                lblName.Text = objDocument.FileName;
                                txtDescription.Text = objDocument.FileDescription;
                                txtCategory.Text = objDocument.Category;
                                ddlCategories.Text = objDocument.Category;
                                if (objDocument.UserId != -1)
                                {
                                    lblOwner.Text = "None_Specified";
                                }
                                else
                                {
                                    lblOwner.Text = Convert.ToString( objDocument.UserId );
                                }

                                ckbShared.Checked = objDocument.Share;

                                if (objDocument.Share)
                                {
                                    // txtShareCode.Text = objDocument.ShareCode;
                                    txtShareCode.Enabled = true;
                                }
                                else
                                {
                                    txtShareCode.Text = "";
                                    //txtShareCode.Enabled = false;
                                }

                                txtKeywords.Text = objDocument.Keywords;
                                // security violation attempt to access item not related to this Module
                            }
                        }
                    }
                    else
                    {
                        txtShareCode.Enabled = false;

                        plName.Visible = false;
                        lblName.Visible = false;
                        cmdDelete.Visible = false;
                        cmdUpdate.Text = "Create";
                    }

                    // Category controls initialization

                    ckbFreeText.Checked = false;
                    inputHidden.Value = "txtCategoryInvisible";
                    txtCategory.Style["visibility"] = "hidden";
                    ddlCategories.Style["visibility"] = "visible";
                }
                else
                {
                    if (fileUpload.HasFile)
                    {
                        //fileUpload.

                        // fileUpload.PostedFile = fileUpload.PostedFile;
                    }
                }
            }

            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException( this, exc );
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdCancel_Click runs when the cancel button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void CmdCancel_Click ( System.Object sender, System.EventArgs e )
        {
            try
            {
                this.Response.Redirect( Globals.NavigateURL( this.TabId ), true );
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException( this, exc );
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void CmdDelete_Click ( System.Object sender, System.EventArgs e )
        {

            try
            {
                //Only attempt to delete the item if it exists already
                if (!Null.IsNull( this.FileId ))
                {
                    DocumentsController objWebLibs = new DocumentsController();
                    objWebLibs.DeleteDocument( PortalId, this.FileId );

                    //refresh cache
                    SynchronizeModule();
                    //this.CacheKey
                    //DataCache.RemoveCache(
                }

                this.Response.Redirect( Globals.NavigateURL( this.TabId ), true );
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException( this, exc );
            }
        }

        private Guid FileId
        {
            get
            {
                return m_fileId;
            }
            set
            {
                m_fileId = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// CmdUpdate_Click runs when the update button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void CmdUpdate_Click ( System.Object sender, System.EventArgs e )
        {
            try
            {
                string g = string.Empty;
                // Only Update if Input Data is Valid
                if (Page.IsValid)
                {
                    DocumentInfo objDocument = new DocumentInfo();
                    DocumentsController controller = new DocumentsController();
                    objDocument = controller.GetDocument( this.FileId );
                    if (objDocument != null)
                    {
                        objDocument = new DocumentInfo();
                        objDocument.FileGuid = this.FileId;
                        objDocument.PortalId = PortalId;
                        objDocument.UserId = UserInfo.UserID;
                        objDocument.CreatedByUser = UserInfo.UserID;

                        // Default ownerid value for new documents is current user, may be changed
                        // by the value of the dropdown list (below)
                        objDocument.UserId = UserId;

                    }
                    else
                    {

                        objDocument = new DocumentInfo();
                        objDocument.FileName = Path.GetFileName( fileUpload.PostedFile.FileName );
                        string extension = Path.GetExtension( fileUpload.PostedFile.FileName ).ToLower();
                        objDocument.Extension = extension;
                        objDocument.PortalId = PortalId;
                        objDocument.UserId = UserInfo.UserID;
                        objDocument.CreatedByUser = UserInfo.UserID;

                        //string extension = Path.GetExtension( fileUpload.PostedFile.FileName ).ToLower();
                        string MIMEType = fileUpload.PostedFile.ContentType;// GetMIMEType( extension );
                        //buffer to hold Document Contents
                        byte[] content = new byte[fileUpload.PostedFile.InputStream.Length];
                        //Store the Content of the Document in a buffer
                        //This buffer will be stored in the Database
                        fileUpload.PostedFile.InputStream.Read( content, 0, content.Length );
                        objDocument.ContentType = MIMEType;
                        objDocument.ByteSize = content.Length;
                        objDocument.Content = content;

                        if (lstOwner.Visible)
                        {
                            if (lstOwner.SelectedValue != String.Empty)
                            {
                                objDocument.UserId = Convert.ToInt32( lstOwner.SelectedValue );
                                objDocument.CreatedByUser = UserInfo.UserID;
                            }
                            else
                            {
                                objDocument.UserId = -1;
                                objDocument.CreatedByUser = objDocument.UserId;
                            }
                        }
                        else
                        {
                            // User never clicked "change", leave ownedbyuserid as is
                        }
                    }

                    objDocument.FileDescription = txtDescription.Text;
                    if (inputHidden.Value == "txtCategoryVisible")
                        objDocument.Category = txtCategory.Text;
                    else
                        objDocument.Category = ddlCategories.Text;

                    objDocument.Share = ckbShared.Checked;


                    if (ckbShared.Checked)
                    {
                        objDocument.ShareCode = txtShareCode.Text;
                    }
                    else
                    {
                        objDocument.ShareCode = string.Empty;
                    }

                    objDocument.Keywords = txtKeywords.Text;

                    // Create an instance of the Document DB component

                    if (DotNetNuke.Common.Utilities.Null.IsNull( this.FileId ))
                        controller.AddDocument( objDocument );
                    else
                        controller.UpdateDocument( objDocument );


                    // url tracking
                    //UrlController objUrls = new UrlController();

                    //objUrls.UpdateUrl(PortalId, ctlUrl.Url, ctlUrl.UrlType, ctlUrl.Log, ctlUrl.Track, PortalId, ctlUrl.NewWindow);

                    SynchronizeModule();



                    //Redirect back to the portal home page
                    this.Response.Redirect( Globals.NavigateURL( this.TabId ), true );
                }
            }

            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException( this, exc );
            }
        }

        #endregion



        protected void CkbShared_CheckedChanged ( object sender, EventArgs e )
        {
            txtShareCode.Enabled = ckbShared.Checked;
        }

        protected void FileUpload_DataBinding ( object sender, EventArgs e )
        {
            string a = string.Empty;
        }

        protected void TxtDescription_Load ( object sender, EventArgs e )
        {

        }





    }
}

